package com.ek.kademlia.handlers;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ek.common.AbstractMessageHandler;
import com.ek.common.Context;
import com.ek.common.task.AddContact;
import com.ek.kademlia.protocol.impl.DiscoveryMessage;
import com.ek.kademlia.protocol.impl.DiscoveryMessageResponse;
import com.ek.service.mina.ComunicationService;

public class DiscoveryMessageHandler extends AbstractMessageHandler<DiscoveryMessage> {
    private static final transient Logger log = LoggerFactory.getLogger(DiscoveryMessageHandler.class);

    public DiscoveryMessageHandler(Context context) {
        super(context);
    }

    @Override
    protected void doExecute(DiscoveryMessage message, SocketAddress address) {
        log.debug("received discovery message from bucket with this socketAddress:" + address);
        getContext().getTaskManager().put(new AddContact(address, message, getContext().getRoutingTable()));
        DiscoveryMessageResponse response = new DiscoveryMessageResponse();
        response.setMessageID(message.getMessageID());
        response.setNodeID(getContext().getNodeID());
        InetSocketAddress socketAddress = (InetSocketAddress) address;
        log.debug("sending discovery response to bucket with this socketAddress:" + socketAddress);
        getContext().getComunicationService().sendResponse(response, new InetSocketAddress(socketAddress.getAddress(), ComunicationService.PORT));
    }

    public static String getMessageClass() {
        return DiscoveryMessage.class.getCanonicalName();
    }
}
